import { useMessageBox } from "@/hooks/message";
import { toLoginRoute } from "@/router/utils";
import { useUserStoreHook } from "@/store/modules/user";
import { router } from "@/router/index";
import { ElNotification } from "element-plus";

// 消息通知工作流任务
function jobNotify(content: any) {
  // 延迟解决可能没有工单数据
  setTimeout(() => {
    const opts: any = {};
    // 任务未办理
    if (content.status === "0") {
      // 运行中
      const jobType = content.jobType === "0" ? "个人任务：" : "角色任务：";
      const type = "warning";
      const msg =
        '<a href="#" style="color:#FF4500;">' +
        '<i class="iconfont icon-xianshimima"></i>&nbsp;' +
        jobType +
        content.data +
        "</a>" +
        "，请及时处理";
      handleNotify(opts, type, msg);
    } else {
      // 发起 或 结束
      const text =
        content.status === "-1"
          ? content.data
          : content.data + "已完成, 请悉知";
      const type = content.status === "-1" ? "warning" : "success";
      const msg = '<a href="#" style="color:#FF4500;">' + text + "</a>";
      handleNotify(opts, type, msg);
    }
  }, 2000);
}

function handleNotify(opts, type, msg) {
  const defOpts = {
    title: "任务提醒",
    type: type,
    dangerouslyUseHTMLString: true,
    message: msg,
    offset: 60
  };
  ElNotification(Object.assign(defOpts, opts));
}

function loginNotify(messageContent: string) {
  if (messageContent === "opened") {
    return;
  }
  let confirmTitle;
  if (messageContent === "replaced") {
    confirmTitle = "当前登录用户已在其他设备登录,请重新登录！";
  } else if (messageContent === "kickout") {
    confirmTitle = "当前登录会话已被踢下线,请重新登录！";
  } else if (messageContent === "disable") {
    confirmTitle = "当前登录用户已被封禁,请重新登录！";
  }
  if (confirmTitle) {
    useMessageBox()
      .confirm(confirmTitle)
      .then(async () => {
        const loginPath = toLoginRoute("/");
        await useUserStoreHook().resetAll();
        await router.push(loginPath);
      });
  }
}

export function notify(message: any) {
  const messageContent = message.content;
  if (message.type === "0") {
    loginNotify(messageContent);
  } else if (message.type === "1") {
    jobNotify(messageContent);
  }
}
